<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\jzshop\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\jzshop\common\ExcelTools;
use app\jzshop\model\Brand;
use app\jzshop\model\GoodsSkuStandby;
use app\jzshop\model\Supplier as SupplierModel;
use think\Db;

/**
 * 供应商控制器
 * @package app\jzshop\admin
 */
class Pricing extends Admin
{
    /**
     * 供应商列表
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        // 查询
        $map = $this->getMap();
        // 排序
        $order = $this->getOrder('id desc');
        // 数据列表
        $data_list = GoodsSkuStandby::where($map)->where('status > 0')->order($order)->paginate();
        $selectSql = Db::getLastSql();
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setSearch([
                'brand_id' => '品牌',
                'itemName' => '商品名称',
                'itemNameAlias' => '商品别名',
                'colour' => '商品颜色',
                'colourAlias' => '商品颜色别名',
                'itemCode' => 'SKU编码',
                'itemCodeAlias' => 'SKU别名',
            ]) // 设置搜索框
            ->addColumns([ // 批量添加数据列
                ['right_button', '操作', 'btn'],
                ['brand_id', '品牌', 'text'],
                ['main_img_alias', '首图', 'picture'],
                ['itemNameAlias', '商品名称', 'text'],
                ['colourAlias', '商品编码', 'text'],
                ['itemCodeAlias', 'SKU编码', 'text'],
                ['supplyPrice', '供应价格', 'text.edit'],
                ['spec', '尺寸', 'text'],
                ['weight', '重量', 'text'],
                ['goods_carriage', '运费', 'text.edit'],
                ['goods_fluctuation', '溢价率', 'text.edit'],

                [
                    'goods_estimate_price',
                    '预估价',
                    'callback',
                    function ($data) {
                        return ($data['goods_carriage'] + $data['supplyPrice']) * $data['goods_fluctuation'];
                    },
                    '__data__'
                ],

                ['sell_market_price', '市场价', 'text.edit'],
                ['sell_friends_price', '友商价', 'text.edit'],
                ['sell_daily_price', '日销价', 'text.edit'],
                ['sell_activity_price', '活动价', 'text.edit'],
                ['sell_coupon_price', '红码价', 'text.edit'],
                ['sell_brokerage_price', '佣金', 'text.edit'],
                ['buy_number', '出售数', 'text.edit'],

                ['right_button', '操作', 'btn']
            ])
            ->addTopButtons('enable,disable') // 批量添加顶部按钮           
            ->addRightButtons('enable,disable') // 批量添加顶部按钮       
            ->addRightButton('view', [
                'title' => '预览',
                'icon' => 'fa fa-fw fa-eye',
                'href' => url('standby/view', ['id' => '__id__'])
            ], ['area' => ['600px', '90%']])
            ->addRightButton('link', [
                'title' => '聚水潭',
                'icon' => 'fa fa-fw fa-rss-square',
                'target' => '_blank',
                'href' => 'https://gyl.scm121.com/channel/goodsDetailNew/__itemSpuId__?itemCoId=__coId__'
            ])
            ->addRightButton('custom', [
                'title' => '推送',
                'icon' => 'fa fa-fw fa-upload',
                'class' => 'ajax-get',
                'href' => url('standby/push', ['type' => 'push', 'id' => '__id__'])
            ])
            ->addRightButton('custom', [
                'title' => '更新',
                'icon' => 'fa fa-fw fa-arrow-up',
                'class' => 'ajax-get',
                'href' => url('standby/push', ['type' => 'update', 'id' => '__id__'])
            ])
            ->addRightButton('custom', [
                'title' => '更新头图',
                'icon' => 'fa fa-fw fa-arrow-up',
                'class' => 'ajax-get',
                'href' => url('standby/push', ['type' => 'updateimage', 'id' => '__id__'])
            ])
            ->addRightButton('custom', [
                'title' => '合并logo',
                'icon' => 'fa fa-fw fa-image-o',
                'class' => 'ajax-get',
                'href' => url('/jzshop/brand/conflates', ['goods_id' => '__id__'])
            ])
            ->addTopButton('push', [
                'title' => '批量推送',
                'icon' => 'fa fa-fw fa-upload',
                'field' => 'id',
                'target-form' => 'ids',
                'class' => 'btn btn-success ajax-post confirm',
                'href' => url('standby/push', ['type' => 'push'])
            ])
            ->addTopButton('push', [
                'title' => '导出筛选',
                'icon' => 'fa fa-fw fa-upload',
                'class' => 'btn btn-success',
                'href' => url('download', ['type' => 'select', 'sql' => base64_encode($selectSql)]),
            ])
            ->addTopButton('push', [
                'title' => '导出所有',
                'icon' => 'fa fa-fw fa-upload',
                'class' => 'btn btn-success',
                'href' => url('download', ['type' => 'all']),
            ])
            ->addOrder(['supplierId' => 'asc', 'itemSpuId' => 'asc', 'itemId' => 'desc'])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }
    public function download()
    {
        $type = $this->request->param('type', 'all');

        $data_list = [];
        switch ($type) {
            case 'select':
                $sql = $this->request->param('sql', false);
                if ($sql) {
                    $data_list = Db::query(base64_decode($sql));
                } else {
                    $this->error('参数错误');
                }
                break;
            case 'all':
            default:
                $data_list = GoodsSkuStandby::field('*')->where('sell_market_price > 0')->order('update_time desc')->select()->toArray();
        }

        $title = [
            [
                'title' => '供应商',
                'name' => 'weight',
                'func' => function () {
                    return '绵阳市城市马帮餐饮管理有限公司';
                }
            ],
            [
                'title' => '品牌',
                'name' => 'brand_id',
                'func' => function ($value) {
                    if ($value) {
                        $brand = Brand::column('name', 'id');
                        return $brand[$value];
                    } else {
                        return '';
                    }
                }
            ],
            [
                'title' => '商品别名',
                'name' => 'itemNameAlias',
                'func' => function ($value, $data) {
                    return $data['itemNameAlias'] . '|' . $data['colourAlias'];
                }
            ],
            [
                'title' => '产品说明',
                'name' => 'colourAlias',
                'func' => function ($value, $data) {
                    return $data['itemNameAlias'] . '|' . $data['colourAlias'];
                }
            ],
            ['title' => '物料编码', 'name' => 'itemCodeAlias'],
            ['title' => '市场价', 'name' => 'sell_market_price'],
            ['title' => '友商价', 'name' => 'sell_friends_price'],
            ['title' => '日销价', 'name' => 'sell_daily_price'],
            ['title' => '活动价', 'name' => 'sell_activity_price'],
            ['title' => '红码价', 'name' => 'sell_coupon_price'],
            ['title' => '佣金', 'name' => 'sell_brokerage_price'],
            [
                'title' => '佣金比例',
                'name' => 'main_img_alias',
                'func' => function () {
                    return 0;
                }
            ],

            // ['title' => '佣金比例', 'name' => 'main_img_alias', 'func' => function () {
            //     return 0;
            // }],
        ];
        // dump($data_list);die;
        $EXCEL = ExcelTools::outputProjectExcel($data_list, ['titles' => $title, 'file_name' => '城市马帮-物料录入登记-']);
        ExcelTools::downloadExcel($EXCEL, '城市马帮-物料录入登记-' . date('Y_m_d_His'));
    }

    /**
     * 新增
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function add()
    {
        // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();

            $goods_imgs_file_ids = explode(',', $data['goods_imgs_file']);

            foreach ($goods_imgs_file_ids as $file_id) {
                $res = SupplierModel::saveData($file_id);
            }

            if ($res) {
                $this->success('新增成功', 'index');
            } else {
                $this->error('新增失败', 'index');
            }
        }

        // 显示添加页面
        return ZBuilder::make('form')
            ->addFormItems([
                ['files', 'goods_imgs_file', '商品资料包',],
            ])
            ->fetch();
    }
    public function quickEdit($record = [])
    {
        $param = $this->request->param();
        $res = GoodsSkuStandby::where(['id' => $param['pk']])->update([$param['name'] => $param['value']]);
        if (false !== $res) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }
}
